﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Dict.DataModel;
using ProtoBuf.Message;

namespace UI
{
    public class AllHerosPage : Page
    {
        public UIScrollView scrollView;
        public UIScrollView buffExplainScrollView;
        public GameObject buffExplain;
        public GameObject itemBuffExplain;
        public GameObject itemPrefab;
        public SimpleGrid simpleGrid;
        public SimpleGrid buffEcplainSimpleGrid;
        public GameObject[] tabs;
        public GameObject[] chosed;
        public GameObject pointer;
        public bool isBtn;

        public delegate void GoBattleCallback(int index);
        public GoBattleCallback m_callback;

        List<TableHero> heroList = new List<TableHero>();
        List<List<TableHero>> world = new List<List<TableHero>>();
        List<string> idList = new List<string>();

        List<TableBuffExplaination> BuffList = new List<TableBuffExplaination>();

        int curShowedCount = 0;

        IEnumerator UpdatePanel(int tab = 0)
        {
            foreach (var item in simpleGrid.childs)
            {
                Destroy(item);
            }
            simpleGrid.childs.Clear();
            AssetLoad.ResourceManager.Instance.UnloadUnusedResources();
            //yield return new WaitForSeconds(waitTime);
            List<TableHero> curList = world[tab];
            
            int count = 0;
            for (int i = 0; i < curList.Count; i++)
            {
                GameObject obj = Instantiate(itemPrefab);
                simpleGrid.AddChild(obj);
                obj.SetActive(true);
                obj.name = curList[i].id;
                var script = obj.GetComponent<RecruitResultCardItem>();
                script.SetHeroBuyId(curList[i].id, UnGetted(curList[i].id));
                count++;
                if (count % 14 == 0)
                    yield return 1;
            }
            itemPrefab.SetActive(false);
            curShowedCount += count;
            scrollView.ResetPosition();
        }

        IEnumerator UpdateBuffExplainPanel()
        {
            foreach (var item in buffEcplainSimpleGrid.childs)
            {
                Destroy(item);
            }
            buffEcplainSimpleGrid.childs.Clear();
            AssetLoad.ResourceManager.Instance.UnloadUnusedResources();


            int count = 0;
            for (int i = 0; i < BuffList.Count; i++)
            {
                GameObject obj = Instantiate(itemBuffExplain);
                buffEcplainSimpleGrid.AddChild(obj);
                obj.SetActive(true);
                obj.name = BuffList[i].BuffId;
                var script = obj.GetComponent<ResultBuffItem>();
                script.SetBuffById(BuffList[i]);
                count++;
                if (count%30==0)
                {
                    yield return 1;
                }
            }
                itemBuffExplain.SetActive(false);
                curShowedCount += count;
                buffExplainScrollView.ResetPosition();
        }

        protected override void DoOpen()
        {
            base.DoOpen();
            Room.RoomManager.Switch(SceneType.CARD_VIEW);
            if (isBtn)
                return;
            GetComponent<PageTweener>().Play();

            curShowedCount = 0;

            for(int i = 0;i< tabs.Length; i++)
            {
                tabs[i].GetComponent<UIEventListener>().onClick = SetChosedState;
            }

            CSWarriorHandbook msg = new CSWarriorHandbook();
            NetAPI.SendHttp(OpDefine.CSWarriorHandbook, msg, (pack, bSuccess) =>
            {
                if (bSuccess)
                {
                    SCWarriorHandbook _msg = pack.kBody as SCWarriorHandbook;
                    idList = _msg.idList;
                    SetHeroList();
                    StopCoroutine("UpdatePanel");
                    StartCoroutine(UpdatePanel());
                }
            });
            BuffList = GetAllBuff();
        }

        void SetHeroList()
        {
            heroList = StaticData.playerData.InstPlayerData.GetAllHeros();
            world.Clear();
            for (int i = 0; i < 3; i++)
                world.Add(new List<TableHero>());
            for (int i = 0; i < heroList.Count; i++)
            {
                if (heroList[i].space == 1 && heroList[i].quality > (int)QualityValue.GREEN)
                    world[0].Add(heroList[i]);//sao
                else if (heroList[i].space == 2 && heroList[i].quality > (int)QualityValue.GREEN)
                    world[1].Add(heroList[i]);//alo
                else if (heroList[i].space == 3 && heroList[i].quality > (int)QualityValue.GREEN)
                    world[2].Add(heroList[i]);//ggo
                else
                    Debug.LogError("Error hero Space:" + heroList[i].space);
            }
        }

        bool UnGetted(string id)
        {
            for(int i = 0;i < idList.Count; i++)
            {
                if (id == idList[i])
                {
                    return false;
                }
            }
            return true;
        }

        protected override void DoClose()
        {
            foreach (var item in simpleGrid.childs)
            {
                Destroy(item);
            }
            simpleGrid.childs.Clear();

            base.DoClose();
        }

        public void SetChosedState(GameObject obj)
        {
            for (int i = 0; i < chosed.Length; i++)
            {
                chosed[i].SetActive(false);
            }
            int flag = int.Parse(obj.name);
            chosed[flag].SetActive(true);
            pointer.transform.localPosition = new Vector3(-7.5f, 216 - 60 * flag, 0);
            switch (flag)
            {
                case 0:
                case 1:
                case 2:
                    scrollView.gameObject.SetActive(true);
                    buffExplain.SetActive(false);
                    StopCoroutine("UpdatePanel");
                    StartCoroutine(UpdatePanel(flag));
                    break;
                case 3:                   
                    scrollView.gameObject.SetActive(false);
                    buffExplain.SetActive(true);
                    StopCoroutine("UpdateBuffExplainPanel");
                    StartCoroutine(UpdateBuffExplainPanel());
                    break;
                default:
                    Debug.LogError("Error Table Left:" + flag);
                    break;
            }
            
        }


        public List<TableBuffExplaination> GetAllBuff()
        {
            List<TableBuffExplaination> list = new List<TableBuffExplaination>();
            foreach (var item in Dict.DictDataManager.Instance.tableBuffExplainationDao.CacheList)
            {
                    if (string.IsNullOrEmpty(item.BuffId))
                    {
                        Debug.LogWarning("buff资源为空：" + item.BuffId);
                        continue;
                    }
                    list.Add(item);    
            }
            return list;
        }
    }
}

